package com.glsc.ngateway.platform.service.it;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class SequenceService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 根据序列名称，求下一个值
    public int getNextValue(String key) {
        String sql = "update t_it_sequence set seq_value = seq_value + 1 where seq_name = ?";
        int count = jdbcTemplate.update(sql, new Object[]{key});
        if (count == 0) {
            // 第一次
            sql = "insert into t_it_sequence(seq_name, seq_value) values(?, 1);";
            jdbcTemplate.update(sql, new Object[]{key});
            return 1;
        } else {
            sql = "select seq_value from t_it_sequence where seq_name = ?";
            Integer value = jdbcTemplate.queryForObject(sql, new Object[]{key}, Integer.class);
            return value;
        }
    }

//    // 根据序列名称，求下一个值
//    public int getNextValue(String key, String type) {
//        String sql = "update t_sequence set seq_value = seq_value + 1 where seq_name = ?";
//        int count = jdbcTemplate.update(sql, new Object[]{key});
//        // 第一次
//        if (count == 0) {
//            if (type == null) {
//                sql = "insert into t_sequence(seq_name, seq_value) values(?, 1);";
//                jdbcTemplate.update(sql, new Object[]{key});
//            } else {
//                sql = "insert into t_sequence(seq_name, seq_type, seq_value) values(?, ?, 1);";
//                jdbcTemplate.update(sql, new Object[]{key, type});
//            }
//            return 1;
//        } else {
//            sql = "select seq_value from t_sequence where seq_name = ?";
//            Integer value = jdbcTemplate.queryForObject(sql, new Object[]{key}, Integer.class);
//            return value;
//        }
//    }
//
//    // 根据序列类型，求所有的序列名称
//    public List<String> getSequenceNamesByType(String seqType) {
//        String sql = "select seq_name from t_sequence where seq_type= ?";
//        List<String> result = jdbcTemplate.queryForList(sql, new Object[]{seqType}, String.class);
//        return result;
//    }
}
